package com.bjpowernode.shop.utils;

import cn.hutool.core.util.RandomUtil;
import com.bjpowernode.shop.properties.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Configuration
public class UploadUtils {

    @Autowired
    private MinioProperties properties;

    // public String upload(MultipartFile file){
    //     return this.upload(file,null);
    // }

    public String upload(MultipartFile file, @Nullable String filename) {
        System.out.println("properties = " + properties);
        try {
            MinioClient minioClient =
                    MinioClient.builder()
                            // Minio的url地址
                            .endpoint(properties.getEndpoint())
                            .credentials(properties.getAccessKey(), properties.getSecretKey())
                            .build();

            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build());
            if (found) {
                log.info("Bucket already exists.");
            } else {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
            }

            String newFileName = "";

            if (StringUtils.isBlank(filename)) {
                // 文件名称
                // 如果有传递过来，那么就用它，如果没有传递，则随机生成一个
                // 可以采用时间戳+随机字符串的方式来生成
                // String random = RandomStringUtils.random(6);

                String random = RandomUtil.randomString(6);
                
                // 为什么要生成文件名称呢？防止相同名称的文件，后上传的会将之前的覆盖
                String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));

                // 获取文件后缀名 123.png
                String suffix = file.getOriginalFilename().substring(
                        file.getOriginalFilename().lastIndexOf(
                                "."
                        )
                );

                newFileName = now + random + suffix;
            } else
                newFileName = filename;
            
            // 获取文件的字节数组
            byte[] bytes = file.getBytes();

            // 通过字节数组，获取输入流对象
            InputStream inputStream = new ByteArrayInputStream(bytes);

            // 上传图片
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(properties.getBucketName())
                            .object(newFileName)
                            .stream(inputStream, inputStream.available(), -1)
                            .contentType("image/jpg")
                            .build());

            inputStream.close();

            // 返回文件的访问路径
            return properties.getHostName() + newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
